package ymos.mytracker.utli;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class GetPlayerList {
	private static byte[] queryPacket= {-1, -1, -1, -1, 85, 0, 0, 0, 0};
	private static DatagramSocket socket;
	
	public static List<String> connect(String ip,int port) throws IOException {
		socket = new DatagramSocket();
		socket.setSoTimeout(5000);
		socket.send(getPacket(queryPacket,ip,port));
		byte[] buf = new byte[1000];
		DatagramPacket packet = new DatagramPacket(buf, buf.length);
		socket.receive(packet);
		//System.out.println(packet.getAddress());
		buf = Arrays.copyOf(packet.getData(), packet.getLength());
		if(buf.length!=queryPacket.length) {
			return null;
		}
		buf[4]=85;
		socket.send(getPacket(buf,ip,port));
		socket.receive(packet);
		buf = Arrays.copyOf(packet.getData(), packet.getLength());
		//System.out.println(Arrays.toString(buf));
		return getPlayer(buf);
		
	}
	
	private static List<String> getPlayer(byte[] data) throws UnsupportedEncodingException {
		if(data.length<7)return null;
		List<String>player = new ArrayList<>();
		int temp=7;
		int n=4;
		for(int i=7;i<data.length-7;i++) {
			if(data[i]==0) {
				byte p[] = new byte[i-temp];
				System.arraycopy(data, temp, p, 0, i-temp);
				if(n==4) {
					String str = new String(p,"UTF-8");
					player.add(str);
					n=0;
				}else {
					n++;
				}
				temp=i+1;
			}
		}
		return player;
		//System.out.println(new String(data,"UTF-8"));
		//System.out.println(Arrays.toString(data));
		//System.out.println(Arrays.toString("��ǧ����ҹ".getBytes()));
	}
	
	private static DatagramPacket getPacket(byte[] data,String ip,int port) throws UnknownHostException {
		return new DatagramPacket(data, data.length, InetAddress.getByName(ip),port);
	}
}
